#!/usr/bin/env python

from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
from fabric.colors import *

import configparser
import time
import logging
import os
import json

env.hosts = ['192.168.1.150']
env.user = 'pi'
env.port = 22
env.password = 'raspberry'

local_path = './packages'
remote_path = '/home/pi/fsc-system'

# logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
filename = '%s/log/%s.log' % (os.getcwd(),
                              time.strftime("%Y%m%d", time.localtime()))
logging.basicConfig(level=logging.INFO,  # 控制台打印的日志级别
                    filename=filename,
                    filemode='a',  # 模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志
                    format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                    )


logger = logging.getLogger(__name__)


def fabWriteConfig(local_path):
    """写入配置文件中"""
    try:
        path = '%s/conf/fab.ini' % os.getcwd()
        logger.info('read config file: %s' % path)
        config = configparser.ConfigParser()
        config.read(path)
        config.set("fab", "local_path", local_path)
        # 写入并保存文件到当前项目文件夹下
        with open(path, 'w') as fw:
            config.write(fw)
    except Exception as e:
        QMessageBox.warning(self, "错误", "%s" % e, QMessageBox.Yes)

def fabReadConfig():
    # 读取配置文件
    try:
        path = '%s/conf/fab.ini' % os.getcwd()
        logger.info('read config file: %s' % path)
        config = configparser.ConfigParser()
        config.read(path)
        fab_config = config['fab']
        global local_path
        global remote_path
        env.hosts = json.loads(fab_config['hosts']) if 'hosts' in fab_config else ['192.168.1.150']
        env.user = fab_config['user'] if 'user' in fab_config else 'pi'
        env.port = int(fab_config['port']) if 'port' in fab_config else 22
        env.password = fab_config['password'] if 'password' in fab_config else 'raspberry'
        local_path = fab_config['local_path'] if 'local_path' in fab_config else 'local_path'
        remote_path = fab_config['remote_path'] if 'remote_path' in fab_config else 'remote_path'
        # return hosts, user, port, password, local_path, remote_path
    except Exception as e:
        logger.error(e)

@task                           # 本地打包任务函数，只限执行一次
@runs_once
def tar_task():
    with lcd("/data"):
        local("tar -czf test.tar.gz test.txt")

@task
def put_task(local_path, remote_path):                 # 上传文件任务函数
    # run("mkdir -p /data/logs")
    # with cd("/data/logs"):
    with settings(warn_only=True):  # put（上传）出现异常时继续执行，不终止
        result = put(local_path=local_path, remote_path=remote_path)
    # 出现异常时，确认用户是否继续，（Y继续）
    if result.failed and not confirm("put file failed, Continue[Y/N]?"):
        abort("Aborting file put task!")

# @task
# def check_task():  # 校验文件任务函数
#     with settings(warn_only=True):
#         #本地local命令需要配置capture=True才能捕获返回值
#         lmd5 = local("md5sum /data/test.tar.gz", capture=True).split(' ')[0]
#         rmd5 = run("md5sum /data/logs/test.tar.gz").split(' ')[0]
#     if lmd5 == rmd5:
#         print("OK")
#     else:
#         print("ERROR")

@task
def web():
    # 上传文件
    put_task('%s/dist.zip' % local_path, '%s/web/dist.zip' % remote_path)
    with cd(remote_path):
        run('sudo docker-compose stop web')
    with cd('%s/web' % remote_path):
        run('sudo rm -r dist')
        run('unzip dist.zip')
        run('sudo rm -r dist.zip')
    with cd(remote_path):
        run('sudo docker-compose up -d web')
        # 清除所有None镜像
        # run('sudo docker rmi $(sudo docker images -q -f dangling=true)')

@task
def server():
    fabReadConfig()
    put_task('%s/server.zip' % local_path, '%s/server.zip' % remote_path)
    # 编译server
    with cd('/home/pi/fsc-system'):
        # 关闭server 容器
        run('sudo docker-compose stop server')
        # 删除
        run('sudo rm -r server')
        # 解压
        run('unzip server.zip')
        # 删除压缩包
        run('sudo rm -r server.zip')
        # 编译server
        run('sudo docker-compose build server')
        # 运行server
        run('sudo docker-compose up -d server')
        # 清除所有None镜像
        # run('sudo docker rmi $(sudo docker images -q -f dangling=true)')

@task
def up_all():
    fabReadConfig()
    web()
    server()
    with cd(remote_path):
        run('sudo docker-compose up -d')
        # 清除所有None镜像
        run('sudo docker rmi $(sudo docker images -q -f dangling=true)')
        

